package com.eric.springboot.config.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eric.springboot.dao.UserMapper;
import com.eric.springboot.dao.UserRoleMapper;
import com.eric.springboot.entity.Role;
import com.eric.springboot.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author Eric
 * @date 2021.2.2
 * 用于查询数据库验证用户
 */
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public JwtUserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userMapper.selectOne(new QueryWrapper<>(new User().setUserName(s)));
        if (user != null){
            List<Role> roles = userRoleMapper.selectRolesByUserId(user.getId());
            user.setRoles(roles);
            return new JwtUserDetails(user);
        }
        throw new UsernameNotFoundException("用户不存在");
    }
}
